//
//  BDShopMapViewController.m
//  iOS_beboy
//
//  Created by wen on 2017/11/10.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDShopMapViewController.h"
#import <AMap2DMap-NO-IDFA/MAMapKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "DOPDropDownMenu.h"
#import "BDShopSearchViewController.h"
#import "BDLocationServer.h"
#import "BDCityInfo.h"
#import "BDButtonAlert.h"
#import "BDUserModel.h"
#import "BDMapAnnotation.h"
#import "BDMapAnnotationView.h"
#import "BDShopTableViewCell.h"
#import "BDShopInfoDeatilViewController.h"
#import "CallExternalProcessBehavior.h"

@interface BDShopMapViewController ()<MAMapViewDelegate, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate, DOPDropDownMenuDelegate, DOPDropDownMenuDataSource>
{
    CGPoint beginDropPoint;
    
    NSArray *_typeArray;
    NSArray *_areaArray;
    NSArray *_sortArray;
    
    NSInteger _currentType;
    NSInteger _currentAreaIndex;
    NSInteger _currentSort;
    
    NSString *_currentCity;
    double _mapCenterLongitude;
    double _mapCenterLatitude;//这两个值用来记录地图中心点
    double _assumeLocationLongitude;
    double _assumeLocationLatitude;//这两个值用来设置请求列表数据时使用当前位置坐标的值
    
    BOOL _isRefreshDatasource;
    
    double _minMapLatRadius;
}
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) UIView *naviView;
@property (nonatomic, strong) UIView *naviTouchView;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *menuView;
@property (nonatomic, strong) NSMutableArray *datasource;
@property (nonatomic, strong) UIButton *bottomButton;
@property (nonatomic, strong) UIPanGestureRecognizer *pan;
@property (nonatomic, strong) NSMutableArray *annotations;
@property (nonatomic, strong) DOPDropDownMenu *menu;
@property (nonatomic, strong) UIButton *resetlocationButton;
@property (nonatomic, strong) UIButton *changeLocationButton;

@property (nonatomic, strong) UIView *seletedAnnotationView;
@property (nonatomic, strong) UITableView *littleTableView;
@property (nonatomic, strong) UIButton *daohangButton;
@property (nonatomic, strong) BDShopModel *seletedShop;

@end

static CGFloat tableTop1;
static CGFloat tableTop2;
static CGFloat tableTop3;
static CGFloat mapMaxHeight;
static CGFloat mapMinHeight;
static CGFloat bottomButtonHeight;
static CGFloat menuHeight;
@implementation BDShopMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    bottomButtonHeight = 49;
    menuHeight = 44;
    tableTop1 = kBDTopHeight + menuHeight;
    tableTop2 = (284 + kBDStatusBarHeight) / 1.0 / 375 * kBDScreenWidth;
    tableTop3 = kBDScreenHeight - kBDTabBarHeight;
    mapMaxHeight = kBDScreenHeight - kBDTabBarHeight;
    mapMinHeight = tableTop2;
    
    _currentSort = 0;
    _currentAreaIndex = 0;
    
    _annotations = [NSMutableArray array];
    _datasource = [NSMutableArray array];
    [self _initUI];
    [self bindRAC];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    if ([BDLocationServer whetherOpenLocationServer] == NO) {
        [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示") message:ASLocalizedString(@"您未开启定位权限，无法精确查看附近商家，若要获得更好体验，请前往设置开启。") type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定") otherTitle:nil clickBlock:^(NSInteger index) {
            
        }];
    }
    
    NSString *lastCity = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastCity"];
    if (![_currentCity isEqualToString:lastCity]) {
        _currentCity = lastCity;
    }
    [self resetMenuData];
    [self startLocation];
}

- (void)resetMenuData{
//    BDCityInfo *cityInfo = [BDCityInfo getCityWithName:_currentCity type:BDCityTypeCity];
//    NSArray *districArray = [BDCityInfo getCityArrayWithParentId:cityInfo.infoID];
//    NSMutableArray *districNameArray = [NSMutableArray array];
//    for (BDCityInfo *districInfo in districArray) {
//        [districNameArray addObject:districInfo.name];
//    }
//    _areaDistrictArray = districNameArray;
    _sortArray = @[ASLocalizedString(@"智能排序"), ASLocalizedString(@"评价最高"), ASLocalizedString(@"距离最近"), ASLocalizedString(@"价格最低")];
    _areaArray = @[@"1 km",@"3 km",@"5 km",@"10 km", @"15 km"];
    _typeArray = @[ASLocalizedString(@"全部"), ASLocalizedString(@"水疗"), @"KTV", ASLocalizedString(@"夜总会"), ASLocalizedString(@"酒吧"), ASLocalizedString(@"沐足"), ASLocalizedString(@"其他")];
    NSString *currentType = [[NSUserDefaults standardUserDefaults] objectForKey:@"shopAndPostType"];
    _currentType = [_typeArray indexOfObject:currentType];
    
    [_menuView removeAllSubviews];
    
    _menu = [[DOPDropDownMenu alloc] initWithOrigin:CGPointMake(0, 0) andHeight:menuHeight];
    _menu.delegate = self;
    _menu.dataSource = self;
    _menu.top = 0;
    __weak BDShopMapViewController *weakSelf = self;
    _menu.startBlock = ^(NSInteger menuIndex) {
        weakSelf.menuView.top = kBDTopHeight;
        weakSelf.menuView.height = kBDScreenHeight - kBDTabBarHeight - kBDTopHeight;
    };
    _menu.endBlock = ^{
        weakSelf.menuView.top = kBDTopHeight;
        weakSelf.menuView.height = menuHeight;
    };
    [_menu selectIndexPath:[DOPIndexPath indexPathWithCol:0 row:0 item:0]];
    [_menuView addSubview:_menu];
    
    [_menu selectIndexPath:[DOPIndexPath indexPathWithCol:0 row:0 item:0]];
}

- (void)startLocation{
    BDLocationModel *locationModel = [BDLocationModel getLocationInfo];
    _mapCenterLongitude = locationModel.longitude;
    _mapCenterLatitude = locationModel.latitude;
    _assumeLocationLongitude = locationModel.longitude;
    _assumeLocationLatitude = locationModel.latitude;
    if ([locationModel.city isEqualToString:_currentCity]) {
        [self resetMapCenterAndStartRequest];
    }else{
        CLGeocoder * geocoder = [[CLGeocoder alloc] init];
        [geocoder geocodeAddressString:_currentCity completionHandler:^(NSArray *placemarks, NSError *error) {
            if(error) {
                [self resetMapCenterAndStartRequest];
                return ;
            }
            if([placemarks count] == 0) {
                [self resetMapCenterAndStartRequest];
                return ;
            }
            CLPlacemark * placeMark = [placemarks objectAtIndex:0];
            _mapCenterLongitude = placeMark.location.coordinate.longitude;
            _mapCenterLatitude = placeMark.location.coordinate.latitude;
            _assumeLocationLongitude = placeMark.location.coordinate.longitude;
            _assumeLocationLatitude = placeMark.location.coordinate.latitude;
            [self resetMapCenterAndStartRequest];
        }];
    }
}

- (void)resetMapCenterAndStartRequest{
    [self resetMapVisibleMapRectWithHeight:_tableView.top];
    [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(_mapCenterLatitude, _mapCenterLongitude)];
    [self requestMapDatasource];
    [self requestTableDatasource];
}

- (void)_initUI{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight - kBDTabBarHeight) style:UITableViewStylePlain];
    _tableView.top = tableTop2;
    _tableView.height = kBDScreenHeight - kBDNavBarHeight - _tableView.top;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self requestTableDatasource];
    }];
    _tableView.backgroundColor = self.view.backgroundColor;
    _tableView.scrollEnabled = NO;
    [_tableView registerClass:[BDShopTableViewCell class] forCellReuseIdentifier:@"shopCell"];
    _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.view addSubview:_tableView];
    
    _menuView = [[UIView alloc] initWithFrame:CGRectMake(0, kBDTopHeight + menuHeight, kBDScreenWidth, 0)];
    _menuView.clipsToBounds = YES;
    [self.view addSubview:_menuView];
    
    _pan = [[UIPanGestureRecognizer alloc] init];
    _pan.delegate = self;
    [_tableView addGestureRecognizer:_pan];
    
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, mapMaxHeight)];
    _mapView.delegate = self;
    _mapView.centerCoordinate = CLLocationCoordinate2DMake(23.117055306224895, 113.2759952545166);
    _mapView.showsUserLocation = YES;
    _mapView.showsCompass = NO;
    _mapView.showsScale = NO;
    MAUserLocationRepresentation *locationRepresntation = [[MAUserLocationRepresentation alloc] init];
    locationRepresntation.showsAccuracyRing = YES;
    [_mapView updateUserLocationRepresentation:locationRepresntation];
    _mapView.zoomLevel = 17.02;
    _mapView.minZoomLevel = 13;
    _mapView.maxZoomLevel = 20;
    [self.view insertSubview:_mapView belowSubview:_tableView];
    
    _resetlocationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_resetlocationButton setBackgroundImage:[UIImage imageNamed:@"dingwei"] forState:UIControlStateNormal];
    _resetlocationButton.size = CGSizeMake(34, 34);
    _resetlocationButton.left = 10;
    _resetlocationButton.top = _mapView.bottom - 15;
    [_mapView addSubview:_resetlocationButton];
    
    _naviView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, kBDTopHeight)];
    _naviView.backgroundColor = [UIColor colorWithRed:54/255.0 green:54/255.0 blue:54/255.0 alpha:1.0f];
    _naviView.layer.shadowColor = [UIColor colorWithRed:54/255.0 green:54/255.0 blue:54/255.0 alpha:1.0f].CGColor;
    _naviView.layer.shadowOffset = CGSizeMake(0, 0);
    _naviView.layer.shadowOpacity = 1;
    _naviView.layer.shadowRadius = 5;
    _naviView.bottom = 0;
    [self.view addSubview:_naviView];
    
    _naviTouchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth - 40, 30)];
    _naviTouchView.centerX = kBDScreenWidth / 2.0;
    _naviTouchView.centerY = kBDStatusBarHeight + kBDNavBarHeight / 2.0;
    _naviTouchView.backgroundColor = [UIColor colorWithHexString:@"#494949"];
    _naviTouchView.layer.cornerRadius = 3;
    _naviTouchView.layer.masksToBounds = YES;
    
    float imageWidth = 15;
    
    UILabel *label1 = [[UILabel alloc] init];
    label1.font = [UIFont systemFontOfSize:13];
    label1.textColor = [UIColor colorWithHexString:@"#bbbbbb"];
    label1.text = ASLocalizedString(@"输入商家");
    [label1 sizeToFit];
    label1.centerY = _naviTouchView.height / 2.0;
    label1.centerX = _naviTouchView.width / 2.0 + (10 + imageWidth) / 2.0;
    [_naviTouchView addSubview:label1];
    
    UIImageView *searchImageView1 = [[UIImageView alloc] init];
    searchImageView1.size = CGSizeMake(15, 15);
    searchImageView1.image = [UIImage imageNamed:@"search_white"];
    searchImageView1.centerY = label1.centerY;
    searchImageView1.right = label1.left - 10;
    [_naviTouchView addSubview:searchImageView1];
    [_naviView addSubview:_naviTouchView];
    
    _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth - 20, 44)];
    _topView.top = kBDStatusBarHeight + 5;
    _topView.centerX = kBDScreenWidth / 2.0;
    _topView.backgroundColor = [UIColor whiteColor];
    _topView.layer.shadowColor = [UIColor colorWithRed:54/255.0 green:54/255.0 blue:54/255.0 alpha:0.5f].CGColor;
    _topView.layer.shadowOffset = CGSizeMake(0, 1);
    _topView.layer.shadowOpacity = 1;
    _topView.layer.shadowRadius = 2;
    _topView.layer.cornerRadius = 3;
    
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:13];
    label.textColor = [UIColor colorWithHexString:@"#bbbbbb"];
    label.text = ASLocalizedString(@"输入商家");
    [label sizeToFit];
    label.centerY = _topView.height / 2.0;
    label.centerX = _topView.width / 2.0 + (10 + imageWidth) / 2.0;
    [_topView addSubview:label];
    
    UIImageView *searchImageView = [[UIImageView alloc] init];
    searchImageView.size = CGSizeMake(15, 15);
    searchImageView.image = [UIImage imageNamed:@"search_gray"];
    searchImageView.centerY = label.centerY;
    searchImageView.right = label.left - 10;
    [_topView addSubview:searchImageView];
    [self.view addSubview:_topView];
    
    _changeLocationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _changeLocationButton.size = CGSizeMake(120, 30);
    [_changeLocationButton setTitle:ASLocalizedString(@"在此区域搜索") forState:UIControlStateNormal];
    [_changeLocationButton setTitleColor:KBDColorBlue forState:UIControlStateNormal];
    _changeLocationButton.titleLabel.font = [UIFont systemFontOfSize:11];
    _changeLocationButton.centerX = self.view.width / 2.0;
    _changeLocationButton.top = _topView.bottom + 10;
    _changeLocationButton.hidden = YES;
    _changeLocationButton.backgroundColor = [UIColor whiteColor];
    _changeLocationButton.layer.shadowColor = [UIColor colorWithRed:54/255.0 green:54/255.0 blue:54/255.0 alpha:0.5f].CGColor;
    _changeLocationButton.layer.shadowOffset = CGSizeMake(0, 1);
    _changeLocationButton.layer.shadowOpacity = 1;
    _changeLocationButton.layer.shadowRadius = 2;
    _changeLocationButton.layer.cornerRadius = 3;
    [self.view addSubview:_changeLocationButton];
    
    _bottomButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _bottomButton.size = CGSizeMake(kBDScreenWidth, bottomButtonHeight);
    _bottomButton.backgroundColor = [UIColor whiteColor];
    [_bottomButton setTitle:ASLocalizedString(@"点击展开更多商家") forState:UIControlStateNormal];
    [_bottomButton setTitleColor:[UIColor colorWithHexString:@"#4c4c4c"] forState:UIControlStateNormal];
    _bottomButton.titleLabel.font = [UIFont systemFontOfSize:15];
    _bottomButton.layer.shadowColor = [UIColor colorWithRed:54/255.0 green:54/255.0 blue:54/255.0 alpha:0.5f].CGColor;
    _bottomButton.layer.shadowOffset = CGSizeMake(0, 0);
    _bottomButton.layer.shadowOpacity = 1;
    _bottomButton.layer.shadowRadius = 2;
    _bottomButton.top = kBDScreenHeight - kBDTabBarHeight + 5;
    [self.view addSubview:_bottomButton];
    
    _seletedAnnotationView = [[UIView alloc] init];
    _seletedAnnotationView.backgroundColor = [UIColor clearColor];
    _seletedAnnotationView.size = CGSizeMake(kBDScreenWidth, 125);
    _seletedAnnotationView.bottom = kBDScreenHeight - kBDTabBarHeight;
    _seletedAnnotationView.hidden = YES;
    [self.view addSubview:_seletedAnnotationView];
    
    UIView *whiteView = [[UIView alloc] init];
    whiteView.backgroundColor = [UIColor whiteColor];
    whiteView.size = CGSizeMake(kBDScreenWidth, 100);
    whiteView.bottom = _seletedAnnotationView.height;
    [_seletedAnnotationView addSubview:whiteView];
    
    _littleTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    _littleTableView.size = CGSizeMake(kBDScreenWidth, 90);
    _littleTableView.bottom = _seletedAnnotationView.height;
    _littleTableView.delegate = self;
    _littleTableView.dataSource = self;
    _littleTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    if (@available(iOS 11.0, *)) {
        _littleTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
    _littleTableView.backgroundColor = [UIColor whiteColor];
    _littleTableView.scrollEnabled = NO;
    [_littleTableView registerClass:[BDShopTableViewCell class] forCellReuseIdentifier:@"shopCell"];
    _littleTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [_seletedAnnotationView addSubview:_littleTableView];
    
    _daohangButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _daohangButton.titleLabel.numberOfLines = 0;
    [_daohangButton setTitle:ASLocalizedString(@"立即\n导航") forState:UIControlStateNormal];
    [_daohangButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _daohangButton.backgroundColor = [UIColor orangeColor];
    _daohangButton.titleLabel.font = [UIFont systemFontOfSize:12];
    _daohangButton.size = CGSizeMake(43, 43);
    _daohangButton.right = _seletedAnnotationView.width - 22;
    _daohangButton.layer.masksToBounds = YES;
    _daohangButton.layer.cornerRadius = _daohangButton.width / 2.0;
    [_seletedAnnotationView addSubview:_daohangButton];
}

- (void)refreshTableDatasource{
    _isRefreshDatasource = YES;
    self.startPage = @"1";
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self requestTableDatasource];
    }];
    [self requestTableDatasource];
}

/*
 http://api.beboy.me/api/shops?page=1&size=100&order=1&user_lng=113.332977&user_lat=23.132472&lng=113.332982&lat=23.132471&lng_radius=0.001984&lat_radius=0.001479&user_city_id=440100&type=0
 
 http://api.beboy.me/api/shops?page=1&size=100&order=1&user_lng=113.332977&user_lat=23.132472&lng=113.332982&lat=23.133620&lng_radius=0.001984&lat_radius=0.000525&user_city_id=440100&type=5
 */

//请求地图数据
- (void)requestMapDatasource{
    NSString *city_id = [BDLocationServer getCityIdWithCityName:[[NSUserDefaults standardUserDefaults] objectForKey:@"lastCity"] cityType:BDCityTypeCity];
    BDLocationModel *locationModel = [BDLocationModel getLocationInfo];
    double userLongitude = self.mapView.userLocation.location.coordinate.longitude == 0 ? locationModel.longitude : self.mapView.userLocation.location.coordinate.longitude;
    double userLatitude = self.mapView.userLocation.location.coordinate.latitude == 0 ? locationModel.latitude : self.mapView.userLocation.location.coordinate.latitude;
    //type
    NSString *typeString = _typeArray[_currentType];
    NSInteger typeIndex = [BDButtonAlert getTypeidWitTypeString:typeString];
    
    if (_minMapLatRadius == 0) {
        _minMapLatRadius = self.mapView.region.span.latitudeDelta / 2.0;
    }
    
    NSString *url = [NSString stringWithFormat:@"%@shops?page=1&size=100&order=1&user_lng=%f&user_lat=%f&lng=%f&lat=%f&lng_radius=%f&lat_radius=%f&user_city_id=%@&type=%@", KBDBaseURL, userLongitude, userLatitude, self.mapView.region.center.longitude, self.mapView.region.center.latitude, self.mapView.region.span.longitudeDelta / 2.0, _minMapLatRadius, city_id, @(typeIndex)];
    BDLog(@"当前地图请求的url:%@", url);
    NSString *headValid = [BDUserModel getHeaderValidation];
    RACSignal *signal = [[BDNetworkingServer v2_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        [self.mapView removeAnnotations:self.annotations];
        [self.annotations removeAllObjects];
        
        BDMapAnnotation *s = [[BDMapAnnotation alloc] init];
        s.coordinate = CLLocationCoordinate2DMake(_assumeLocationLatitude, _assumeLocationLongitude);
        [self.annotations addObject:s];
        
        NSArray *newShops = [BDShopModel mj_objectArrayWithKeyValuesArray:x[@"list"]];
        
        for (BDShopModel *shop in newShops) {
            BDMapAnnotation *a1 = [[BDMapAnnotation alloc] init];
            a1.coordinate = CLLocationCoordinate2DMake(shop.latitude, shop.longitude);
            a1.title = shop.title;
            a1.subtitle = shop.address;
            a1.shop = shop;
            [self.annotations addObject:a1];
        }
        [_mapView addAnnotations:_annotations];
    }];
    [signal subscribeError:^(NSError * _Nullable error) {
        BDLog(@"请求数据失败, error:%@", error);
    }];
}

//请求列表数据
- (void)requestTableDatasource{
    NSString *city_id = [BDLocationServer getCityIdWithCityName:[[NSUserDefaults standardUserDefaults] objectForKey:@"lastCity"] cityType:BDCityTypeCity];
    //type
    NSString *typeString = _typeArray[_currentType];
    NSInteger typeIndex = [BDButtonAlert getTypeidWitTypeString:typeString];
    
    NSString *url = [NSString stringWithFormat:@"%@shops?page=%@&size=%@&order=%@&type=%@&user_lng=%f&user_lat=%f&user_city_id=%@", KBDBaseURL, self.startPage, self.pageSize, @(_currentSort + 1), @(typeIndex), _assumeLocationLongitude, _assumeLocationLatitude, city_id];
    
    //区域和距离
    NSString *disString = _areaArray[_currentAreaIndex];
    url = [url stringByAppendingString:[NSString stringWithFormat:@"&distance=%@", [disString componentsSeparatedByString:@" "].firstObject]];

    NSString *headValid = [BDUserModel getHeaderValidation];
    RACSignal *signal = [[BDNetworkingServer v2_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        if ([_tableView.mj_header isRefreshing] || _isRefreshDatasource == YES) {
            [_tableView.mj_header endRefreshing];
            _isRefreshDatasource = NO;
            [self.datasource removeAllObjects];
        }
        if ([_tableView.mj_footer isRefreshing]) {
            [_tableView.mj_footer endRefreshing];
        }
        [self.datasource addObjectsFromArray:[BDShopModel mj_objectArrayWithKeyValuesArray:x[@"list"]]];
        [self.tableView reloadData];
        self.isEnd = [x[@"is_end"] boolValue];
        self.startPage = x[@"next_page"];
        [self setTableiewFooterViewStateFor:self.tableView datasourceCount:self.datasource.count];
    }];
    [signal subscribeError:^(NSError * _Nullable error) {
        BDLog(@"请求数据失败, error:%@", error);
    }];
}

- (void)bindRAC{
    [[_pan rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        
        //返回的是相对于self.view的偏移量
        CGPoint point = [_pan translationInView:self.view] ;
        
        if (_tableView.top > tableTop1) {
            [self changeTableTop:point];
        }else if (_tableView.top == tableTop1) {
            if (_tableView.contentOffset.y > 0) {
                //减少tableview的contentOffset
                 [self changeTableOffset:point];
            }else if (_tableView.contentOffset.y == 0) {
                if (_menuView.height == menuHeight && point.y < 0) {
                    //向上滑动
                    [self changeTableOffset:point];
                    _tableView.scrollEnabled = YES;
//                    _pan.enabled = NO;
                }else {
                    //向下滑动
                    //这里分情况，如果
                    [self changeTableTop:point];
                }
            }
        }
        //每次移动完成之后需要将偏移量清零（如果不清零，偏移量是叠加的）
        [_pan setTranslation:CGPointZero inView:self.view];
    }];
    
    [[_bottomButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        _mapCenterLongitude = _assumeLocationLongitude;
        _mapCenterLatitude = _assumeLocationLatitude;
        _changeLocationButton.hidden = YES;
        [UIView animateWithDuration:0.2 animations:^{
            _tableView.top = tableTop2;
            _tableView.height = kBDScreenHeight - kBDNavBarHeight - _tableView.top;
            _bottomButton.top = kBDScreenHeight - kBDTabBarHeight + 5;
        } completion:^(BOOL finished) {
            [self resetMapVisibleMapRectWithHeight:tableTop2];
            [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(_mapCenterLatitude, _mapCenterLongitude)];
            [self requestMapDatasource];
        }];
    }];
    
    [[_resetlocationButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        //回归定位点
        _changeLocationButton.hidden = YES;
        if (_mapView.userLocation.location.coordinate.longitude == 0) {
            BDLocationModel *locationModel = [BDLocationModel getLocationInfo];
            _mapCenterLongitude = locationModel.longitude;
            _mapCenterLatitude = locationModel.latitude;
        }else{
            _mapCenterLongitude = _mapView.userLocation.location.coordinate.longitude;
            _mapCenterLatitude = _mapView.userLocation.location.coordinate.latitude;
        }
        [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(_mapCenterLatitude, _mapCenterLongitude)];
        [self requestMapDatasource];
    }];
    
    [[_changeLocationButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        //隐藏按钮
        _changeLocationButton.hidden = YES;
        //修改定位大头针位置
        BDMapAnnotation *s = _annotations.firstObject;
        s.coordinate = CLLocationCoordinate2DMake(_assumeLocationLatitude, _assumeLocationLongitude);
//        [_mapView showAnnotations:_annotations animated:NO];
        //重新请求数据
        _assumeLocationLatitude = _mapCenterLatitude;
        _assumeLocationLongitude = _mapCenterLongitude;
        [self refreshTableDatasource];
        //拉起列表
        [UIView animateWithDuration:0.2 animations:^{
            _tableView.top = tableTop2;
            _tableView.height = kBDScreenHeight - kBDNavBarHeight - _tableView.top;
            _bottomButton.top = kBDScreenHeight - kBDTabBarHeight + 5;
        } completion:^(BOOL finished) {
            [self resetMapVisibleMapRectWithHeight:tableTop2];
            [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(_mapCenterLatitude, _mapCenterLongitude)];
            [self requestMapDatasource];
        }];
    }];
    
    [[_daohangButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [CallExternalProcessBehavior routeNavigationWithLongitue:_seletedShop.longitude latitue:_seletedShop.latitude];
    }];
}

- (void)changeTableOffset:(CGPoint)point{
    CGFloat newOffset = _tableView.contentOffset.y - point.y;
    [_tableView setContentOffset:CGPointMake(0, MAX(0, newOffset))];
}

- (void)changeTableTop:(CGPoint)point{
    
    if (_tableView.top == tableTop1 && !(_menuView.height == 0 && point.y > 0)) {
        //menu
        float newMenuHeight = _menuView.height - point.y;
        newMenuHeight = MAX(newMenuHeight, 0);
        newMenuHeight = MIN(newMenuHeight, menuHeight);
        _menuView.height = newMenuHeight;
        _menuView.bottom = kBDTopHeight + menuHeight;
    }else{
        //降低tableview高度
        CGFloat newTop = point.y + _tableView.top;
        newTop = MAX(newTop, tableTop1);
        newTop = MIN(newTop, tableTop3);
        _tableView.top = newTop;
        _tableView.height = kBDScreenHeight - kBDNavBarHeight - _tableView.top;
        [self resetMapVisibleMapRectWithHeight:_tableView.top];
    }
    
    //topView
    if (_tableView.top < tableTop2 - 50) {
        if (_topView.bottom > 0) {
            [UIView animateWithDuration:0.1 animations:^{
                _topView.bottom = 0;
            }];
        }
    }else{
        if (_topView.top < kBDStatusBarHeight + 5) {
            [UIView animateWithDuration:0.1 animations:^{
                _topView.top = kBDStatusBarHeight + 5;
            }];
        }
    }
    
    _naviView.bottom = kBDTopHeight * 2 - _tableView.top + _menuView.height;
    if (_pan.state == UIGestureRecognizerStateEnded) {
        [self _animatedFinished];
    }
}

- (void)_animatedFinished{
    float s1 = (tableTop2 - tableTop1)/2.0 + tableTop1;
    float s2 = (tableTop3 - tableTop2)/2.0 + tableTop2;
    float stopY = 0;
    
    if (_tableView.top < s1) {
        stopY = tableTop1;
    }else if (_tableView.top > s2) {
        stopY = tableTop3;
    }else{
        stopY = tableTop2;
    }
    BOOL firstResetMap = stopY > _tableView.top;
    if (firstResetMap) {
        [self resetMapVisibleMapRectWithHeight:stopY];
    }
    [UIView animateWithDuration:0.2 animations:^{
        _tableView.top = stopY;
        _tableView.height = kBDScreenHeight - kBDNavBarHeight - _tableView.top;
        if (stopY == tableTop3) {
            _bottomButton.bottom = kBDScreenHeight - kBDTabBarHeight;
        }
        if (_tableView.top < tableTop2 - 50) {
            _topView.bottom = 0;
        }else{
            _topView.top = kBDStatusBarHeight + 5;
        }
        _naviView.bottom = kBDTopHeight * 2 - _tableView.top + _menuView.height;
        //            if (stopY == tableTop1) {
        //                _naviView.bottom = kBDTopHeight;
        //            }else{
        //                _naviView.bottom = kBDTopHeight * 2 - _tableView.top;
        //            }
    } completion:^(BOOL finished) {
        if (!firstResetMap) {
            [self resetMapVisibleMapRectWithHeight:stopY];
        }
        if (stopY == tableTop1) {
            [UIView animateWithDuration:0.1 animations:^{
                _menuView.height = menuHeight;
                _menuView.bottom = kBDTopHeight + menuHeight;
                _naviView.bottom = kBDTopHeight;
            }];
            
        }else if (stopY == tableTop2) {
            [UIView animateWithDuration:0.1 animations:^{
                _menuView.height = 0;
                _menuView.bottom = kBDTopHeight + menuHeight;
                _naviView.bottom = kBDTopHeight * 2 - _tableView.top;
            }];
        }
        if (stopY == tableTop3) {
            [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(_mapCenterLatitude, _mapCenterLongitude)];
            [self requestMapDatasource];
        }
    }];
}

- (void)resetMapVisibleMapRectWithHeight:(float)mapHeight{
    if (mapMaxHeight >= tableTop2) {
        MAMapPoint point = _mapView.visibleMapRect.origin;
        _mapView.height = MIN(mapHeight, mapMaxHeight);
        MAMapSize size = _mapView.visibleMapRect.size;
        [_mapView setVisibleMapRect:MAMapRectMake(point.x, point.y, size.width, size.height)];
        _resetlocationButton.bottom = MIN(_mapView.height - 10, kBDScreenHeight - kBDTabBarHeight - bottomButtonHeight - 10);
    }
}

#pragma mark -----------------------map代理-------------------------------
- (void)mapView:(MAMapView *)mapView mapWillZoomByUser:(BOOL)wasUserAction{
    if (wasUserAction == YES) {
        if (_tableView.top < tableTop3) {
            _tableView.top = tableTop3;
            _bottomButton.bottom = kBDScreenHeight - kBDTabBarHeight;
            [self resetMapVisibleMapRectWithHeight:_tableView.top];
        }
    }
}

- (void)mapView:(MAMapView *)mapView mapWillMoveByUser:(BOOL)wasUserAction{
    if (wasUserAction == YES) {
        if (_tableView.top < tableTop3) {
            _tableView.top = tableTop3;
            _bottomButton.bottom = kBDScreenHeight - kBDTabBarHeight;
            [self resetMapVisibleMapRectWithHeight:_tableView.top];
        }
    }
}

- (void)mapView:(MAMapView *)mapView mapDidZoomByUser:(BOOL)wasUserAction {
    if (wasUserAction == YES) {
        _mapCenterLongitude = _mapView.centerCoordinate.longitude;
        _mapCenterLatitude = _mapView.centerCoordinate.latitude;
        _minMapLatRadius = self.mapView.region.span.latitudeDelta / 2.0;
        if (_mapCenterLatitude != _assumeLocationLatitude || _mapCenterLongitude != _assumeLocationLatitude) {
            _changeLocationButton.hidden = NO;
        }
        [self requestMapDatasource];
    }
}

- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction{
    if (wasUserAction == YES) {
        _mapCenterLongitude = _mapView.centerCoordinate.longitude;
        _mapCenterLatitude = _mapView.centerCoordinate.latitude;
        if (_mapCenterLatitude != _assumeLocationLatitude || _mapCenterLongitude != _assumeLocationLatitude) {
            _changeLocationButton.hidden = NO;
        }
        [self requestMapDatasource];
    }
}

/*
 @brief 根据anntation生成对应的View
 @param mapView 地图View
 @param annotation 指定的标注
 @return 生成的标注View
 */
- (MAAnnotationView*)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    BDLog(@"当前大头针数量：%@", @(_mapView.annotations.count));
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
//        NSString *typeString = _typeArray[_currentType];
//        NSInteger typeIndex = [BDButtonAlert getTypeidWitTypeString:typeString];
//        if (((BDMapAnnotation *)annotation).shop.type != typeIndex && typeIndex != 0) {
//            return nil;
//        }
        
        static NSString *pointReuseIndetifier = @"customReuseIndetifier";
        BDMapAnnotationView *annotationView = (BDMapAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[BDMapAnnotationView alloc] initWithAnnotation:annotation                                                 reuseIdentifier:pointReuseIndetifier];
        }
        annotationView.canShowCallout = NO;
        if (((BDMapAnnotation *)annotation).shop) {
            annotationView.needShowImage = YES;
            if (((BDMapAnnotation *)annotation).shop.type < BDShopTypeOther) {
                annotationView.image = [UIImage imageNamed:[NSString stringWithFormat:@"annotation%zd.png", ((BDMapAnnotation *)annotation).shop.type]];
            }else{
                annotationView.image = [UIImage imageNamed:@"annotation_small.png"];
            }
            if (_seletedShop && ((BDMapAnnotation *)annotation).shop.shop_id == _seletedShop.shop_id) {
                [annotationView setSelected:YES animated:YES];
            }else{
                [annotationView setSelected:NO animated:YES];
            }
            
        }else{
            annotationView.needShowImage = NO;
            annotationView.image = [UIImage imageNamed:@"location_datouzhen.png"];
        }
        return annotationView;
    }
    return nil;
}

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view{
    if ([view isKindOfClass:[BDMapAnnotationView class]]) {
        if (((BDMapAnnotation *)view.annotation).shop) {
//            BDLog(@"这里是有shop数据的");
            _seletedShop = ((BDMapAnnotation *)view.annotation).shop;
            _seletedAnnotationView.hidden = NO;
            [self resetMapVisibleMapRectWithHeight:_seletedAnnotationView.top + 25];
            [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(_mapCenterLatitude, _mapCenterLongitude)];
            if (_tableView.top < tableTop3) {
                _resetlocationButton.top = _mapView.bottom - 15;
                _tableView.top = tableTop3;
                _tableView.height = kBDScreenHeight - kBDNavBarHeight - _tableView.top;
                _bottomButton.bottom = kBDScreenHeight - kBDTabBarHeight;
                [self requestMapDatasource];
            }
            [_littleTableView reloadData];
        }
    }
}

//- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view {
//    /* Adjust the map center in order to show the callout view completely. */
//    if ([view isKindOfClass:[BDMapAnnotationView class]]) {
//        BDMapAnnotationView *cusView = (BDMapAnnotationView *)view;
//        CGRect frame = [cusView convertRect:cusView.calloutImageView.frame toView:self.mapView];
////        frame = UIEdgeInsetsInsetRect(frame, UIEdgeInsetsMake(kCalloutViewMargin, kCalloutViewMargin, kCalloutViewMargin, kCalloutViewMargin));
//        if (!CGRectContainsRect(self.mapView.frame, frame)) {
//            /* Calculate the offset to make the callout view show up. */
//            CGSize offset = [self offsetToContainRect:frame inRect:self.mapView.frame];
//            CGPoint theCenter = self.mapView.center;
//            theCenter = CGPointMake(theCenter.x - offset.width, theCenter.y - offset.height);
//            CLLocationCoordinate2D coordinate = [self.mapView convertPoint:theCenter toCoordinateFromView:self.mapView];
//            [self.mapView setCenterCoordinate:coordinate animated:YES];
//        }
//    }
//}

- (void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate{
//    BDLog(@"点击了地图");
    if (_tableView.top < tableTop3) {
        [self resetMapVisibleMapRectWithHeight:tableTop3];
        _tableView.top = tableTop3;
        _tableView.height = kBDScreenHeight - kBDNavBarHeight - _tableView.top;
        _bottomButton.bottom = kBDScreenHeight - kBDTabBarHeight;
        [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(_mapCenterLatitude, _mapCenterLongitude)];
        [self requestMapDatasource];
    }
    if (_seletedShop) {
        _seletedShop = nil;
        _seletedAnnotationView.hidden = YES;
        [self resetMapVisibleMapRectWithHeight:tableTop3];
        [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(_mapCenterLatitude, _mapCenterLongitude)];
        [self requestMapDatasource];
    }
}

#pragma mark -----------------------tableView代理-------------------------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _tableView) {
        return _datasource.count;
    }else{
        if (_seletedShop) {
            return 1;
        }
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableView) {
        BDShopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"shopCell" forIndexPath:indexPath];
        [cell configeWithModel:self.datasource[indexPath.row] index:indexPath.row];
        return cell;
    }else{
        if (_seletedShop) {
            BDShopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"shopCell" forIndexPath:indexPath];
            [cell configeWithModel:_seletedShop index:-2];
            return cell;
        }
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableView) {
        BDShopInfoDeatilViewController *bussinessVC = [[BDShopInfoDeatilViewController alloc]init];
        bussinessVC.hidesBottomBarWhenPushed = YES;
        //商家id
        BDShopModel *shopModel = self.datasource[indexPath.row];
        bussinessVC.shopID = [NSString stringWithFormat:@"%zd", shopModel.shop_id];
        bussinessVC.title = shopModel.title;
        [self.navigationController pushViewController:bussinessVC animated:YES];
    }else{
        if (_seletedShop) {
            BDShopInfoDeatilViewController *bussinessVC = [[BDShopInfoDeatilViewController alloc]init];
            bussinessVC.hidesBottomBarWhenPushed = YES;
            //商家id
            BDShopModel *shopModel = _seletedShop;
            bussinessVC.shopID = [NSString stringWithFormat:@"%zd", shopModel.shop_id];
            bussinessVC.title = shopModel.title;
            [self.navigationController pushViewController:bussinessVC animated:YES];
        }
    }
}

#pragma mark -----------------------scrollview代理-------------------------------
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == _tableView) {
        beginDropPoint = scrollView.contentOffset;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == _tableView) {
        CGPoint currentPoint = CGPointMake(0, beginDropPoint.y - _tableView.contentOffset.y);
        if ((currentPoint.y > 0 && scrollView.contentOffset.y <= 0) || _tableView.top > tableTop1 || _menuView.height < menuHeight) {
            [self changeTableTop:currentPoint];
            [_tableView setContentOffset:CGPointZero];
        }
        beginDropPoint = _tableView.contentOffset;
    }
}

//- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
//    if (scrollView == _tableView) {
//        _tableView.decelerationRate = 0;
//        if (_tableView.top > tableTop1 || _menuView.height < menuHeight) {
//            _tableView.scrollEnabled = NO;
//            [self _animatedFinished];
//        }
//    }
//}

//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//    if (scrollView == _tableView) {
//        if (_tableView.top > tableTop1 || _menuView.height < menuHeight) {
//            _tableView.scrollEnabled = NO;
//            [self _animatedFinished];
//        }
//    }
//}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    if (scrollView == _tableView) {
        if (targetContentOffset->y <= 0) {
            *targetContentOffset = _tableView.contentOffset;
            [_tableView setContentOffset:CGPointMake(0, 0) animated:YES];
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView == _tableView) {
        if (_tableView.top > tableTop1 || _menuView.height < menuHeight) {
            _tableView.scrollEnabled = NO;
            [self _animatedFinished];
        }
    }
}

- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView{
    if (scrollView == _tableView) {
        [self _animatedFinished];
    }
}

#pragma mark -----------------------dropMenu代理-------------------------------
//标题个数
- (NSInteger)numberOfColumnsInMenu:(DOPDropDownMenu *)menu{
    return 3;
}

//每个标题对应的行数
- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column{
    switch (column) {
        case 0:
            return _areaArray.count;
            break;
        case 1:
            return _typeArray.count;
            break;
        case 2:
            return _sortArray.count;
            break;
        default:
            break;
    }
    return 0;
}

//每个标题对应行的内容
- (NSString *)menu:(DOPDropDownMenu *)menu titleForRowAtIndexPath:(DOPIndexPath *)indexPath{
    switch (indexPath.column) {
        case 0:
            return _areaArray[indexPath.row];
            break;
        case 1:
            return _typeArray[indexPath.row];
            break;
        case 2:
            return _sortArray[indexPath.row];
            break;
        default:
            break;
    }
    return nil;
}

//- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfItemsInRow:(NSInteger)row column:(NSInteger)column{
//    if (column == 0) {
//        if (row == 0) {
//            return _areaDistantArray.count;
//        }else if (row == 1) {
//            return _areaDistrictArray.count;
//        }
//    }
//    return 0;
//}
//
//- (NSString *)menu:(DOPDropDownMenu *)menu titleForItemsInRowAtIndexPath:(DOPIndexPath *)indexPath{
//    if (indexPath.column == 1) {
//        if (indexPath.row == 0) {
//            return _areaDistantArray[indexPath.item];
//        }else if (indexPath.row == 1) {
//            return _areaDistrictArray[indexPath.item];
//        }
//    }
//    return nil;
//}

//点击事件
- (void)menu:(DOPDropDownMenu *)menu didSelectRowAtIndexPath:(DOPIndexPath *)indexPath{
    switch (indexPath.column) {
        case 0:
            _currentAreaIndex = indexPath.row;
            break;
        case 1:{
            _currentType = indexPath.row;
            [[NSUserDefaults standardUserDefaults] setObject:_typeArray[_currentType] forKey:@"shopAndPostType"];
            [self requestMapDatasource];
        }break;
        case 2:
            _currentSort = indexPath.row;
            break;
            
        default:
            break;
    }
    [self refreshTableDatasource];
}

#pragma mark -----------------------gesturerecognizer代理-------------------------------
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if (_tableView.scrollEnabled) {
//        BDLog(@"tableview响应开始");
    }else{
//        BDLog(@"手势响应开始");
    }
    return !_tableView.scrollEnabled;
}

#pragma mark -----------------------touch-------------------------------
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = touches.anyObject;
    CGPoint point = [touch locationInView:self.view];
    if (CGRectContainsPoint(_topView.frame, point) || CGRectContainsPoint(_naviTouchView.frame, point)) {
        //点击了topview
        BDShopSearchViewController *searchVC = [[BDShopSearchViewController alloc] init];
        [self.navigationController pushViewController:searchVC animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
